

#include <stdio.h>
#include "common/checked_fileops.h"
#include "import.h"

static const char * allCountriesFileName = "allCountries.txt";
static const char * alternateNamesFileName = "alternateNames.txt";
static const char * coutryInfoFileName = "countryInfo.txt";

static void usage()
{
    fprintf(stdout, "usage: import {out-db-file-name}\n");
}

static void prn_verbose(const char * str)
{
    fputs(str, stdout);
    fputs("\n", stdout);
}

static void prn_error(const char * str)
{
    fputs(str, stderr);
    fputs("\n", stderr);
}

int main(int argc, char ** argv)
{
#ifdef _DEBUG
    argc = 2;
    char * argv2[] = { "", "test" };
    argv = argv2;
#endif

    int result = 0;
    const char * dest_filename = NULL;
    FILE * fdest = NULL;
    FILE * fallCountries = NULL;
    FILE * falternateNames = NULL;
    FILE * fcountryInfo = NULL;

    if (argc < 2)
    {
        fprintf(stderr, "error: destination filename is not specified");
        usage();
        result = -1;
    }
    else
    {
        dest_filename = argv[1];
    }

    // open source files
    CHECKED_OPEN_READ(fallCountries, allCountriesFileName);
    CHECKED_OPEN_READ(falternateNames, alternateNamesFileName);
    CHECKED_OPEN_READ(fcountryInfo, coutryInfoFileName);

    // open dest file
    CHECKED_OPEN_WRITE(fdest, dest_filename);

    if (!result)
    {
        struct ImportContext * ctx = create_import_context(fdest, fallCountries, falternateNames, fcountryInfo, &prn_verbose, &prn_error);

        start_import(ctx);

        free_import_context(ctx);
    }

    // free resources
    CHECKED_CLOSE(fdest);
    CHECKED_CLOSE(fallCountries);
    CHECKED_CLOSE(falternateNames);
    CHECKED_CLOSE(fcountryInfo);

    return result;
}
